package com.yinile.zc04.dao;

import java.util.ArrayList;

import org.springframework.stereotype.Repository;

import com.yinile.zc04.domain.Author;
import com.yinile.zc04.sys.dao.BaseRepository;
import com.yinile.zc04.sys.page.Pagination;
import com.yinile.zc04.sys.utils.StringUtils;

@Repository
public class AuthorRepository extends BaseRepository<Author>{
	

	/**
	 * 保存
	 * @param author
	 */
	public void save(Author author) {
		String sql = "INSERT INTO `db1`.`t_author`"
				+ "(`c_id`,`c_address`,`c_balance`,`c_birthday`,`c_is_vip`,`c_level`,`c_name`)"
				+ "values (?,?,?,?,?,?,?)";
		jdbcTemplate.update(sql, new Object[]{author.id, author.address, author.balance, 
				author.birthday, author.isVip, author.level, author.name});
	}

	
	
	/**
	 * 根据ID查找单个对象  
	 * @param id
	 * @return
	 */
	public Author findById(String id) {
		String sql = "SELECT t.c_id id, t.c_address address,"
				+ "t.c_balance balance,  t.c_birthday birthday,"
				+ "t.c_is_vip isVip,   t.c_level level,"
				+ "t.c_name name FROM db1.t_author t where t.c_id=?";
		return super.queryById(sql, id, Author.class);		
	}

	public void delete(String id) {
		String sql = "delete from db1.t_author where c_id=?";
		this.jdbcTemplate.update(sql, new Object[]{id});
	}

	public void update(Author author) {
		String sql = "update db1.t_author set c_address=?,c_balance=?,c_birthday=?,"
				+ "c_is_vip=?,c_level=?,c_name=? where c_id=?";
		this.jdbcTemplate.update(sql, new Object[]{author.address, author.balance, author.birthday,
				author.isVip, author.level, author.name, author.id});
	}


	/**
	 * 分页查询。强制走从。
	 * @param offset 页码，从零开始计算。
	 * @param step 页面大小
	 * @param name 作者姓名
	 * @param address 作者地址
	 * @return
	 */
	public Pagination<Author> findByPage(Integer offset, Integer step, String name, String address) {
		Pagination<Author> pagination = new Pagination<Author>();
		String sql1 = "/*!mycat:db_type=slave*/ select count(t.c_id) totalRecordCount from db1.t_author t where 1=1";
		String sql2 = "/*!mycat:db_type=slave*/ SELECT t.c_id id, t.c_address address,"
				+ "t.c_balance balance,  t.c_birthday birthday,"
				+ "t.c_is_vip isVip,   t.c_level level,"
				+ "t.c_name name FROM db1.t_author t where 1=1";
		StringBuilder clause = new StringBuilder();
		ArrayList<Object> params = new ArrayList<Object>();
		if (StringUtils.isNotEmpty(name)) {
			clause.append(" and t.c_name like ? ");
			params.add(new StringBuilder("%").append(name).append("%"));
		}
		if (StringUtils.isNotEmpty(address)) {
			clause.append(" and t.c_address like ? ");
			params.add(new StringBuilder("%").append(address).append("%"));
		}
		
		pagination.paging = super.findPaging(offset, step, new StringBuilder(sql1)
				.append(clause).toString(),params);
		
		// 添加了limit子句的sql字符串
		String sbSql = super.addLimit(new StringBuilder(sql2).append(clause).toString(), 
				offset, step, params);
		pagination.data = super.queryList(sbSql, params, Author.class);
		return pagination;
	}

}
